"""
# Reference

[MobileNetV2: Inverted Residuals and Linear Bottlenecks]()

This model is based on the following implementations:
- https://github.com/pytorch/vision/blob/master/torchvision/models/mobilenet.py

"""
from tensorflow.keras import Model, layers, activations, Sequential


def make_divisible(v, divisor, min_value=None):
    """
    This function is taken from the original tf repo.
    It ensures that all layers have a channel number that is divisible by 8
    It can be seen here:
    https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
    :param v:
    :param divisor:
    :param min_value:
    :return:
    """
    if min_value is None:
        min_value = divisor
    new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
    # Make sure that round down does not go down by more than 10%.
    if new_v < 0.9 * v:
        new_v += divisor
    return new_v


class ConvBNReLU(layers.Layer):
    def __init__(self, filters, kernel_size=3, strides=1, padding="same", groups=1):
        super(ConvBNReLU, self).__init__()
        if groups == 1:
            self.conv = layers.Conv2D(filters, kernel_size, strides, padding)
        else:
            self.conv = layers.DepthwiseConv2D(kernel_size, strides, padding)
        self.bn = layers.BatchNormalization()
        self.relu6 = layers.ReLU(max_value=6)

    def call(self, inputs, training=None, **kwargs):
        x = self.conv(inputs)
        x = self.bn(x)
        x = self.relu6(x)
        return x


class InvertedResidual(layers.Layer):
    def __init__(self, inp, oup, strides, expand_ratio):
        super(InvertedResidual, self).__init__()
        self.strides = strides
        assert strides in [1, 2]

        hidden_dim = int(round(inp * expand_ratio))
        self.use_res_connect = self.strides == 1 and inp == oup
        layer_list = []
        if expand_ratio != 1:
            # pw
            layer_list.append(ConvBNReLU(hidden_dim, kernel_size=1))
        layer_list.extend([
            # dw
            ConvBNReLU(hidden_dim, strides=strides, groups=hidden_dim),
            # pw-linear
            layers.Conv2D(oup, 1, 1, "same", use_bias=False),
            layers.BatchNormalization(),
        ])
        self.conv = Sequential(layer_list)

    def call(self, inputs, training=None, **kwargs):
        if self.use_res_connect:
            return inputs + self.conv(inputs)
        else:
            return self.conv(inputs)


class MobileNetV2(Model):

    def __init__(self, num_classes=1000, width_mult=1.0, inverted_residual_setting=None, round_nearest=8, block=None):
        super(MobileNetV2, self).__init__()
        if block is None:
            block = InvertedResidual
        input_channel = 32
        last_channel = 1280
        if inverted_residual_setting is None:
            inverted_residual_setting = [
                # t, c, n, s
                [1, 16, 1, 1],
                [6, 24, 2, 2],
                [6, 32, 3, 2],
                [6, 64, 4, 2],
                [6, 96, 3, 1],
                [6, 160, 3, 2],
                [6, 320, 1, 1],
            ]

        # building first layer
        input_channel = make_divisible(input_channel * width_mult, round_nearest)
        self.last_channel = make_divisible(last_channel * max(1.0, width_mult), round_nearest)
        features = [ConvBNReLU(input_channel, strides=2)]
        # building inverted residual blocks
        for t, c, n, s in inverted_residual_setting:
            output_channel = make_divisible(c * width_mult, round_nearest)
            for i in range(n):
                strides = s if i == 0 else 1
                features.append(block(input_channel, output_channel, strides, expand_ratio=t))
                input_channel = output_channel
        # building last several layers
        features.append(ConvBNReLU(self.last_channel, kernel_size=1))
        # make it nn.Sequential
        self.features = Sequential(features)

        self.avg_pool = layers.AveragePooling2D(1, 1)

        # building classifier
        self.classifier = Sequential([
            layers.Conv2D(num_classes, 1, 1, 'same', activation=activations.softmax),
            layers.Flatten()
        ])

    def call(self, inputs, training=None, **kwargs):
        # This exists since TorchScript doesn't support inheritance, so the superclass method
        # (this one) needs to have a name other than `forward` that can be accessed in a subclass
        x = self.features(inputs)
        # Cannot use "squeeze" as batch-size can be 1 => must use reshape with x.shape[0]
        x = self.avg_pool(x)
        x = self.classifier(x)
        return x
